#include "fileio.h"
#include "QDebug"

QFile* FileIO::userFile=NULL;
QHash<QString,User>*  FileIO::userData=NULL;

bool FileIO::getUserFile()
{
    if(userFile == NULL)
    {

        QString path = QDir::cleanPath(QCoreApplication::applicationDirPath() +
                                       QDir::separator() +
                                       QString("/data") +
                                       QDir::separator() +
                                       QString("/userdata"));
        userFile = new QFile(path);
        if(!userFile->open(QIODevice::ReadWrite))
        {
            delete userFile;
            userFile = NULL;
            qDebug()<<"userdata file open failed!!!";
            userFile->close();
            return false;
        }
        userFile->close();
    }
    return true;
}

void FileIO::getAllUser()
{
    if(!getUserFile())
    {
        delete userData;
        userData =NULL;
        return;
    }

    if(userFile->open(QIODevice::ReadOnly|QIODevice::Truncate))
    {
        delete userData;
        userData = new QHash<QString,User>;
        QDataStream in(userFile);
        while(!in.atEnd())
        {
            QString userName;
            QString account;
            QString password;
            in>>userName>>account>>password;
            userData->insert(account,User(userName,account,password));
        }
        for(auto it = userData->begin();it!=userData->end();it++)
        {
            qDebug()<<it->getUserName()<<","<<it->getAccount()<<"," <<it->getPassword();
        }
    }
    userFile->close();
}

bool FileIO::checkAcount(QString account)
{
    getAllUser();
    return userData->contains(account);
}

bool FileIO::checkPassword(User user)
{
    checkAcount(user.getAccount());
    User data = userData->value(user.getAccount());
    return data.getPassword()==user.getPassword();
}

bool FileIO::insertPassword(User user)
{
    if(!getUserFile())
    {
        delete userData;
        userData =NULL;
        return false;
    }
    if( checkAcount(user.getAccount()))
    {
        return false;
    }
    if(userFile->open(QIODevice::Append))
    {
        user.setUserName("NULL");
        QDataStream out(userFile);
        out<<user.getUserName()<<user.getAccount()<<user.getPassword();
    }
    userFile->close();
    return true;
}
